package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;


    @Override
    public Map search(Map<String, String> searchMap) {



        if (searchMap != null) {

            //构建布尔查询
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            //布尔查询中需要用到模糊查询 match(字段类型，具体值即传入参数)
            if(StringUtils.isNotEmpty(searchMap.get("keywords"))){
                boolQuery.must(QueryBuilders.matchQuery("name", searchMap.get("keywords")).operator(Operator.AND));

            }

            //条件筛选：品牌
            if(StringUtils.isNotEmpty(searchMap.get("brand"))){
                boolQuery.filter(QueryBuilders.termQuery("brandName",searchMap.get("brand")));
            }

            //条件筛选：规格参数
            for (String key : searchMap.keySet()) {
                if(key.startsWith("spec_")){
                    String value = searchMap.get(key).replace("%2B", "+");
                    boolQuery.filter(QueryBuilders.termQuery(("specMap."+key.substring(5)+".keyword"),value));
                }
            }

            //条件筛选：价格
            if(StringUtils.isNotEmpty(searchMap.get("price"))){
                String[] p = searchMap.get("price").split("-");//0-500
                if (p.length == 2) {
                    boolQuery.filter(QueryBuilders.rangeQuery("price").lte(p[1]));
                }
                boolQuery.filter(QueryBuilders.rangeQuery("price").gte(p[0]));
            }

            //原生搜索实现类(第一个参数)
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            nativeSearchQueryBuilder.withQuery(boolQuery);

            //聚合查询
            //品牌聚合
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms("skuBrand").field("brandName"));

            //规格聚合
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms("skuSpec").field("spec.keyword"));

            //实现分页
            String pageNum = searchMap.get("pageNum");//当前页
            if (StringUtils.isEmpty(pageNum)) {
                pageNum = "1";
            }
            String pageSize = searchMap.get("pageSize");//每页显示条数
            if (StringUtils.isEmpty(pageSize)) {
                pageSize = "30";
            }
            /**
             * 第一个参数：当前页 从0开始计算
             * 第二个参数：每页显示条数
             */
            nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum)-1,Integer.parseInt(pageSize)));

            //排序查询
            if(StringUtils.isNotEmpty(searchMap.get("sortField"))&& StringUtils.isNotEmpty(searchMap.get("sortRule"))){
                if("ASC".equals(searchMap.get("sortRule"))){
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.ASC));
                }else{
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.DESC));
                }
            }

            //设置高亮
            HighlightBuilder.Field field = new HighlightBuilder.Field("name").preTags("<span style='color:red'>").postTags("</span>");
            nativeSearchQueryBuilder.withHighlightFields(field);


            /**
             * 第一个参数：条件构建对象
             * 第二个参数：查询操作实体类
             * 第三个参数：查询结果操作对象
             */
            AggregatedPage<SkuInfo> resultInfo = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    //拿到命中的所有数据
                    SearchHits hits = searchResponse.getHits();
                    long total = hits.getTotalHits();
                    Aggregations aggregations = searchResponse.getAggregations();
                    List<T> list = new ArrayList<>();
                    if(hits != null){
                        for (SearchHit hit : hits) {
                            //将单条数据封装成一个SkuInfo对象
                            SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
                            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                            if(highlightFields!=null && highlightFields.size()>0){
                                skuInfo.setName(highlightFields.get("name").getFragments()[0].toString());
                            }

                            list.add((T) skuInfo);
                        }
                    }
                    // new出这个接口的实现类, 关注该返回对象需要哪些参数
                    return new AggregatedPageImpl<T>(list,pageable,total,aggregations);
                }
            });
            Map<String,Object> resultMap = new HashMap<>();
            //查询结果对象
            resultMap.put("rows",resultInfo.getContent());
            //总记录数
            resultMap.put("total",resultInfo.getTotalElements());
            //总页数
            resultMap.put("totalPages",resultInfo.getTotalPages());
            //品牌聚合结果
            StringTerms brandTerms = (StringTerms) resultInfo.getAggregation("skuBrand");
            List<String> brandList = brandTerms.getBuckets().stream().map((bucket) -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("brandList",brandList);
            //规格聚合结果
            StringTerms specTerms = (StringTerms) resultInfo.getAggregation("skuSpec");
            List<String> specList = specTerms.getBuckets().stream().map((bucket) -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("specList",this.formatSpecList(specList));
            //当前页码
            resultMap.put("pageNum",pageNum);
            return resultMap;
        }
       return null;
    }


    public Map formatSpecList(List<String> specList){
        Map<String,Set<String>> resultMap= new HashMap<>();
        for (String specJsonString : specList) {
            //单个json数据转化为map {"颜色":"白色"  ,  "尺码":"150度"}
            Map<String,String> sepcMap = JSON.parseObject(specJsonString, Map.class);
            for (String specKey : sepcMap.keySet()) {
                //{“颜色”，“尺码”} 遍历-->  “颜色”
                //结果集中没存过颜色，就new一个Set集合来存规格值
                Set<String> set = resultMap.get(specKey);
                if(set == null){
                    set = new HashSet<>();
                }
                //把颜色对应的规格值 存入set
                set.add(sepcMap.get(specKey));
                //把{“颜色”：[白色]}
                resultMap.put(specKey,set);
            }
            //这一轮得到的是{“颜色”：[白色]，“尺码”：[150度]}
        }
        //这一轮得到的是{“颜色”：[白色，黄色...]，“尺码”：[150度，200度...]}
        return resultMap;
    }

}
